#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
诊断IP白名单问题
"""

import os
import sys
import logging
import requests
from dotenv import load_dotenv

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from config.settings import settings

logging.basicConfig(level=logging.INFO)

def check_ip_whitelist():
    """检查IP白名单问题"""
    print("🔍 诊断IP白名单问题...")
    print("=" * 50)
    
    print("📋 问题分析:")
    print("1. 错误码: 60020")
    print("2. 错误信息: not allow to access from your ip")
    print("3. 当前IP: 222.222.32.164")
    print("4. 影响接口: 会话状态检查、会话建立、消息发送")
    
    print("\n🔧 根本原因:")
    print("- 企业微信API需要IP白名单授权")
    print("- 当前服务器IP不在白名单中")
    print("- 只有send_msg接口不受IP限制")
    
    print("\n🛠️ 解决方案:")
    print("1. 立即解决:")
    print("   - 在企业微信管理后台添加IP白名单: 222.222.32.164")
    print("   - 路径: 企业微信管理后台 -> 应用管理 -> 客服 -> 设置 -> IP白名单")
    
    print("\n2. 临时解决方案:")
    print("   - 使用send_msg接口（不受IP限制）")
    print("   - 跳过会话状态检查")
    print("   - 直接发送消息")
    
    print("\n3. 长期解决方案:")
    print("   - 配置固定的服务器IP")
    print("   - 申请企业微信API权限")
    print("   - 使用企业微信提供的SDK")

def test_api_access():
    """测试API访问权限"""
    print("\n🧪 测试API访问权限...")
    
    load_dotenv()
    os.environ['WX_CORPID'] = settings.WX_CORPID
    os.environ['WX_CORPSECRET'] = settings.WX_CORPSECRET
    
    # 获取access_token
    url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    params = {
        'corpid': settings.WX_CORPID,
        'corpsecret': settings.WX_CORPSECRET
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        result = response.json()
        
        if result.get('errcode') == 0:
            access_token = result.get('access_token')
            print(f"✅ access_token获取成功: {access_token[:20]}***")
            
            # 测试不同接口的IP限制
            test_apis = [
                ("会话状态检查", "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/get"),
                ("会话转接", "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/trans"),
                ("发送消息", "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg"),
                ("获取客服账号", "https://qyapi.weixin.qq.com/cgi-bin/kf/account/list"),
                ("获取客服人员", "https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/list")
            ]
            
            print("\n📊 API访问测试:")
            for name, api_url in test_apis:
                try:
                    if "send_msg" in api_url:
                        # 发送消息接口需要POST
                        test_data = {
                            "open_kfid": settings.OPEN_KF_ID,
                            "touser": "test_user",
                            "msgtype": "text",
                            "text": {"content": "test"}
                        }
                        resp = requests.post(api_url, params={'access_token': access_token}, json=test_data, timeout=5)
                    else:
                        resp = requests.get(api_url, params={'access_token': access_token}, timeout=5)
                    
                    if resp.status_code == 200:
                        data = resp.json()
                        if data.get('errcode') == 60020:
                            print(f"   {name}: ❌ IP白名单限制")
                        elif data.get('errcode') == 0:
                            print(f"   {name}: ✅ 正常访问")
                        else:
                            print(f"   {name}: ⚠️ 其他错误 ({data.get('errcode')})")
                    else:
                        print(f"   {name}: ❌ 请求失败 ({resp.status_code})")
                        
                except Exception as e:
                    print(f"   {name}: ❌ 请求异常 ({str(e)})")
                    
        else:
            print(f"❌ access_token获取失败: {result}")
            
    except Exception as e:
        print(f"❌ 测试异常: {str(e)}")

def create_workaround():
    """创建临时解决方案"""
    print("\n📝 创建临时解决方案...")
    
    workaround_code = '''
# 临时解决方案：跳过会话状态检查，直接发送消息
def send_kf_message_workaround(self, open_kfid, external_userid, msg_type, content, token=None):
    """
    发送客服消息（临时解决方案，跳过IP限制）
    """
    try:
        if not token:
            token = self.get_access_token()
        if not token:
            logger.error("无法获取access_token")
            return None
        
        url = "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg"
        params = {'access_token': token}
        
        # 生成唯一的msgid
        unique_msgid = f"wx_{int(time.time())}_{uuid.uuid4().hex[:8]}"
        
        data = {
            "open_kfid": open_kfid,
            "touser": external_userid,
            "msgtype": msg_type,
            "text": {"content": content},
            "msgid": unique_msgid
        }
        
        logger.info(f"📤 直接发送消息（跳过会话检查）...")
        logger.info(f"   external_userid: {external_userid}")
        logger.info(f"   content: {content}")
        
        response = self.session.post(url, params=params, json=data, timeout=10)
        result = response.json()
        
        if result.get('errcode') == 0:
            logger.info(f"✅ 消息发送成功")
            return result
        else:
            logger.error(f"❌ 消息发送失败: {result}")
            return None
            
    except Exception as e:
        logger.error(f"❌ 发送消息异常: {str(e)}")
        return None
'''
    
    with open('ip_workaround.py', 'w', encoding='utf-8') as f:
        f.write(workaround_code)
    
    print("✅ 临时解决方案已保存到 ip_workaround.py")

def main():
    """主函数"""
    print("🚀 IP白名单问题诊断工具")
    print("=" * 50)
    
    # 分析问题
    check_ip_whitelist()
    
    # 测试API访问
    test_api_access()
    
    # 创建临时解决方案
    create_workaround()
    
    print("\n🎯 诊断完成!")
    print("请在企业微信管理后台添加IP白名单: 222.222.32.164")

if __name__ == '__main__':
    main() 